package com.zx.zxojbackendjudge.codesandbox.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zx.zxojbackendcommon.exception.BusinessException;
import com.zx.zxojbackendjudge.codesandbox.CodeSandBox;
import com.zx.zxojbackendmodel.dto.judge.ExecuteCodeRequest;
import com.zx.zxojbackendmodel.dto.judge.ExecuteCodeResponse;
import org.apache.commons.lang3.StringUtils;

/**
 * 远程代码沙箱
 */
public class RemoteCodeSandBox implements CodeSandBox {
    private final String AUTH_REQUEST_HEADER = "ACCESS";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");
        String signature = HttpUtil.createGet("http://192.168.88.137:8090/getAuth?name=zhangsan")
                .execute()
                .body();
        System.out.println("签名"+signature);
        String url = "http://192.168.88.137:8090/executeCode";
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        //接口提供方要鉴权，在请求中添加需要的请求参数
        HttpResponse response = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, signature)
                .body(json)
                .execute();
        int status = response.getStatus();
        String responseStr = response.body();
        if(status != 200){
            throw new BusinessException(500, "executeCode remoteSandbox error, message = " + responseStr);
        }
        if (StringUtils.isBlank(responseStr)) {
            throw new BusinessException(500, "executeCode remoteSandbox error, message = " + responseStr);
        }
        System.out.println(responseStr);
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
    }
}

